<script setup>
    import {
        Edit,
        Delete,
        BellFilled,
        Search
    } from '@element-plus/icons-vue'
    import axios from 'axios';
    import {onMounted, ref} from 'vue'
    // 导入 ExcelJS 库
    import ExcelJS from 'exceljs/dist/exceljs.min.js';
    //声明一个异步的函数
    import {
        ExamListBySearchTeacherService,
        ExamAddService,
        ExamUpdateService
    } from '@/api/exam.js'
    import {
        CourseListAllSerivce
    } from '@/api/course.js'
    import {
        StudentListAllSerivce,
        fetchStudentsByMainClass
    } from '@/api/student.js'
    import {
        MainClassListAllSerivce
    } from '@/api/mainClass.js'
    import {
        ProfessionListAllSerivce
    } from '@/api/profession.js'

    import {
        ElMessage,
    } from 'element-plus'
    const exams = ref([{
        "examId":1,
        "examGrade":"",
        "studentId":"",
        "courseId":"",
    }])

    const courses = ref([{
        "courseId":1,
        "courseName":"",
        "courseSemester":"",
        "courseCreditHour":"",
        "teacherId":"",
        "professionId":""
    }])

    const students = ref([{
        "studentId":1,
        "studentName":"",
        "studentPassword":"",
        "studentEmail":"",
        "studentPhone":"",
        "studentSex":"",
        "studentTime":"",
        "studentNation":"",
        "studentNativePlace":"",
        "studentPhoto":"",
        "classId":"",
        "professionId":''
    }])

    const mainClasses = ref([{
        "classId":1,
        "className":"",
        "classNumber":"",
        "teacherId":"",
        "professionId":""
    }])

    const courseAll = async () => {
        try {
            const result = await CourseListAllSerivce();
            courses.value = result.data;
        } catch (error) {
            ElMessage({
                type: 'error',
                message: '搜索出错',
            });
        }
    }

    const studentAll = async () => {
        try {
            const teacherId_args = teacherId;
            const result = await StudentListAllSerivce(teacherId_args);
            students.value = result.data;
        } catch (error) {
            ElMessage({
                type: 'error',
                message: '搜索出错',
            });
        }
    }

    const mainClassAll = async () => {
        try {
            const result = await MainClassListAllSerivce();
            mainClasses.value = result.data;
        } catch (error) {
            ElMessage({
                type: 'error',
                message: '班级搜索出错',
            });
        }
    }

    const tempStudents = ref([{
        "studentId":"",
        "studentName":"",
        "studentPassword":"",
        "studentEmail":"",
        "studentPhone":"",
        "studentSex":"",
        "studentTime":"",
        "studentNation":"",
        "studentNativePlace":"",
        "studentPhoto":"",
        "classId":"",
        "professionId":''
    }])

    const professions = ref([{
        "professionId":1,
        "professionName":"",
        "professionType":""
    }])

    const professionAll = async () => {
        try {
            const result = await ProfessionListAllSerivce();
            professions.value = result.data;
        } catch (error) {
            ElMessage({
                type: 'error',
                message: '专业搜索出错',
            });
        }
    }

     // 监听所选课程变化，获取对应的学生列表
     const handleMianClassChange = async () => {
        try {
            const selectedClassId = examModel.value.classId;
            const result = await fetchStudentsByMainClass(selectedClassId);
            tempStudents.value = result.data;
        } catch (error) {
            ElMessage({
                type: 'error',
                message: '获取学生列表出错',
            });
        }
    }

    const jwtToken = localStorage.getItem('teacherJwtToken');
    // 设置请求头部，包含jwt令牌
    const config = {
        headers: {
            Authorization: `Bearer ${jwtToken}`
        }
    };
    const teacherModel = ref({
        teacherId: '',
        teacherName: '',
        teacherPassword: '',
        teacherPhoto: '',
        teacherPhone:'',
        professionId:1,
        professionName:''
    });
    const fetchData = async () => {
        try {
            const response = await axios.get('http://localhost:9090/teacher/jwt', config);
            const teacherData = response.data.data.teacher;
            if (teacherData) {
                teacherModel.value.teacherId = teacherData.teacherId;
                teacherModel.value.teacherName = teacherData.teacherName;
                teacherModel.value.teacherPassword = teacherData.teacherPassword;
                teacherModel.value.teacherPhone=teacherData.teacherPhone
                teacherModel.value.teacherPhoto = teacherData.teacherPhoto;
                teacherModel.value.professionId=teacherData.professionId;
                professionAll();
                // 获取对应的专业名称并添加到教师对象中
                const profession = professions.value.find(prof => prof.professionId === teacherModel.value.professionId);
                if (profession) {
                    teacherModel.value.professionName = profession.professionName;
                }
                studentAll();
                courseAll();
                mainClassAll();
                search();
            } else {
                console.error('User data not found in the response');
            }
        } catch (error) {
            console.log(error);
        }
    };
     //添加数据模型
     const examModel = ref({
        // examId:'',
        examGrade: 0,
        studentId: 0,
        courseId: 0,
        classId: 0
    })

     //清空模型的数据
     const clearData = () => {
        examModel.value.examGrade = '';
        examModel.value.studentId = '';
        examModel.value.courseId = '';
        examModel.value.classId = '';
    }

    //控制添加弹窗
    const dialogVisible = ref(false)

    const addExam = async () => {
        let result = await ExamAddService(examModel.value);
        if(result.code===1){
            ElMessage.success('添加成功')
        }else{
            ElMessage.error(result.msg)
        }
        search();
        dialogVisible.value = false;
    }

    
    //分页
    const currentPage = ref(1)
    const pageSize = ref(5)
    const total = ref(20)
    const handleSizeChange = (val) => {
        pageSize.value = val;
        // examListByPage(currentPage.value, pageSize.value);
        search();
    }
    const handleCurrentChange = (val) => {
        currentPage.value = val;
        search();
    }

    // examListByPage();
    onMounted(() => {
        fetchData();
    });

  
    const multipleSelection = ref([])
 
    //定义变量，控制标题的展示
    const title = ref('')
    const handleSelectionChange = (val) => {
        multipleSelection.value = val
    }
    // 导出
    const exportSelected = () => {
        if (multipleSelection.value.length === 0) {
            ElMessage({
                type: 'error',
                message: '请选择要导出的数据',
            });
            return;
        }

        // 创建一个新的工作簿
        const workbook = new ExcelJS.Workbook();

        // 添加一个工作表
        const worksheet = workbook.addWorksheet('Sheet1');

        // 设置表头信息
        worksheet.addRow(['课程名称','学生名称','考试成绩']);

        // 获取选择的数据
        const selectedData = multipleSelection.value;

        // 将数据添加到工作表中
        selectedData.forEach(row => {
            worksheet.addRow([
                row.courseName,
                row.studentName,
                row.examGrade,
            ]);
        });

        // 将工作簿保存为Excel文件
        workbook.xlsx.writeBuffer()
            .then(buffer => {
                const blob = new Blob([buffer], {
                    type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
                });
                const fileName = '成绩数据.xlsx';

                // 创建下载链接并触发下载
                const link = document.createElement('a');
                link.href = URL.createObjectURL(blob);
                link.download = fileName;
                link.click();

                ElMessage({
                    type: 'success',
                    message: '导出成功',
                });
            })
            .catch(error => {
                console.error('导出Excel文件时出错:', error);
                ElMessage({
                    type: 'error',
                    message: '导出失败',
                });
            });
    }
      //搜索
    const input = ref("");
    const select = ref("1");
    const teacherId = ref(0);
    const search = async () => {
        try {
            const result = await ExamListBySearchTeacherService(input.value, select.value, teacherModel.value.teacherId, currentPage.value, pageSize.value);
            console.log(result)
            exams.value = result.data.rows;
            total.value = result.data.total;
            // 遍历考试数据，获取对应的学生名称并添加到考试对象中\
            exams.value.forEach(exam => {
                const student = students.value.find(stu => stu.studentId === exam.studentId);
                if (student) {
                exam.studentName = student.studentName;
                }
            });
             // 遍历考试数据，获取对应的课程名称并添加到考试对象中
             exams.value.forEach(exam => {
                const course = courses.value.find(cour => cour.courseId === exam.courseId);
                if (course) {
                exam.courseName = course.courseName;
                }
            });
        } catch (error) {
            ElMessage({
                type: 'error',
                message: '成绩搜索出错',
            });
        }
    }

    //展示编辑弹窗
    const showDialog = (row) => {
        dialogVisible.value = true;
        title.value = '编辑成绩';
        // 数据拷贝
        examModel.value.examGrade = row.examGrade;
        examModel.value.studentId = row.studentId;
        examModel.value.courseId = row.courseId;
        examModel.value.studentName =row.studentName;
        examModel.value.courseName = row.courseName;
        // 扩展ID属性，需要传输给后台
        examModel.value.examId = row.examId;
    }

        //编辑
        const updateExam = async () => {
        //调用接口
        let result = await ExamUpdateService(examModel.value);
        if(result.code===1){
            ElMessage.success('修改成功')
        }else {
            ElMessage.error(result.msg);
        }
        search();
        dialogVisible.value = false;
    }
</script>
<template>
    <div class="card-container">
        <el-card class="page-container">
            <template #header>
                <div class="header">
                    <span style="font-size: 14px;"><b>成绩管理</b></span>
                    <div class="extra">
                        <el-input v-model="input" placeholder="请输入" class="input-with-select">
                            <template #prepend>
                                <el-select v-model="select" placeholder="课程名称" style="width: 115px">
                                    <el-option label="课程名称" value="1" />
                                    <el-option label="学生姓名" value="2" />
                                </el-select>
                            </template>
                            <template #append>
                                <el-button :icon="Search" @click="search(input,select,currentPage,pageSize)" />
                            </template>
                        </el-input>
                        <el-button type="success" @click="exportSelected()" plain>导出</el-button>
                        <el-button type="primary" @click="dialogVisible=true;title='添加成绩';clearData()">添加成绩</el-button>
                    </div>
                </div>
            </template>
            <el-table :data="exams" style="width: 100%" @selection-change="handleSelectionChange">
                <el-table-column type="selection" width="55" />
                <el-table-column label="序号" width="300" type="index"> </el-table-column>
                <el-table-column label="课程名称" width="230" prop="courseName"></el-table-column>
                <el-table-column label="学生姓名" width="230" prop="studentName"></el-table-column>
                <el-table-column label="考试成绩" width="240" prop="examGrade"></el-table-column>
                <el-table-column label="操作" width="150">
                    <template #default="{ row }">
                        <el-button :icon="Edit" circle plain type="primary" @click="showDialog(row)"></el-button>
                        <!-- <el-button :icon="Delete" circle plain type="danger" @click="deleteexam(row)"></el-button> -->
                    </template>
                </el-table-column>
                <template #empty>
                    <el-empty description="没有数据" />
                </template>
            </el-table>
            <el-dialog v-model="dialogVisible" :title="title" width="50%" >
                <el-form :model="examModel" :rules="rules" label-width="100px" style="padding-right: 30px">
                <el-row>
                    <el-col :span="6">
                    <el-form-item label="课程名称" prop="courseId" style="width:200px">
                        <el-select v-model="examModel.courseId" placeholder="课程名称">
                            <el-option
                            v-for="course in courses"
                            :key="course.courseId"
                            :label="course.courseName"
                            :value="course.courseId">
                            </el-option>
                        </el-select>
                    </el-form-item>
                    </el-col>
                    <el-col :span="6">
                    <el-form-item label="班级名称" prop="classId" style="width:200px">
                        <el-select v-model="examModel.classId" placeholder="选择班级" @change="handleMianClassChange">
                            <el-option
                            v-for="mainClass in mainClasses"
                            :key="mainClass.classId"
                            :label="mainClass.className"
                            :value="mainClass.classId">
                            </el-option>
                        </el-select>
                    </el-form-item>
                    </el-col>
                    <el-col :span="6">
                    <el-form-item label="学生姓名" prop="teacherId" style="width:200px">
                        <el-select v-model="examModel.studentId" placeholder="学生姓名">
                            <el-option
                            v-for="student in tempStudents"
                            :key="student.studentId"
                            :label="student.studentName"
                            :value="student.studentId">
                            </el-option>
                        </el-select>
                    </el-form-item>
                    </el-col>
                    <el-col :span="6">
                    <el-form-item label="成绩" prop="examGrade" style="width:400px">
                        <el-input v-model="examModel.examGrade" minlength="1"  style="width:100px"></el-input>
                    </el-form-item>
                    </el-col>
                </el-row>
                </el-form>
                <template #footer>
                    <span class="dialog-footer">
                        <el-button @click="dialogVisible = false">取消</el-button>
                        <el-button type="primary" @click="title=='添加成绩'?addExam():updateExam()"> 确认 </el-button>
                    </span>
                </template>
            </el-dialog>
            
        </el-card>
    </div>
    <el-pagination class="el-p" v-model:current-page="currentPage" v-model:page-size="pageSize"
        :page-sizes="[5, 10, 15, 20]" :background="true" layout="jumper,total, sizes, prev, pager, next " :total="total"
        @size-change="handleSizeChange" @current-change="handleCurrentChange" />
</template>

<style lang="scss" scoped>
    .card-container {
        height: 520px;
        /* 设置合适的固定高度 */
        overflow: auto;
    }

    .page-container {
        min-height: 100%;
        box-sizing: border-box;

        .header {
            display: flex;
            align-items: center;
            justify-content: space-between;

            .extra {
                display: flex;
                align-items: center;

                .el-input {
                    margin-right: 400px;
                }
            }
        }
    }

    .custom-date-picker {
        display: flex;
        width: 100%;
        padding: 0;
        flex-wrap: wrap;
    }

    .el-p {
        margin-top: 20px;
        display: flex;
        justify-content: flex-end;
    }

    .input-with-select {
        background-color: var(--el-fill-color-blank);
    }
    // 调整样式
:deep(.ql-editor) {
  min-height: 180px;
}
:deep(.ql-formats) {
  height: 21px;
  line-height: 21px;
}

</style>